package com.example.LibrarySystem.interceptor;

import com.example.LibrarySystem.Exception.ServiceException;
import com.example.LibrarySystem.annotation.RoleAnnotation;
import com.example.LibrarySystem.mapper.UserMapper;
import com.example.LibrarySystem.pojo.User;
import com.example.LibrarySystem.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 当前角色是否能访问当前接口
 */

@Component
public class RoleInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断当前请求对应的控制器方法上是否有注解
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();

            // 这里使用反射获取方法上的注解信息
            RoleAnnotation annotation = method.getAnnotation(RoleAnnotation.class);
            if (annotation != null) {
                // 如果存在role的注解，则进行相关操作
                String token = request.getHeader("Authorization");
                int id = JwtUtil.verify(token);
                String role = userMapper.getRoleById(id).toLowerCase();

                String type = annotation.type().toLowerCase();

                // 当前用户符合当前接口的角色 就给访问 否则 不给
                if(role.contains(type)){
                    return true;
                }else {
                    throw new ServiceException("-1","没有访问的权限");
                }
            }
        }
        return true;
    }
}
